package com.frx.leetcode.one;

/**
 * @Author: xrf96
 * @Description: 两数相加  https://leetcode-cn.com/problems/add-two-numbers/
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 * @Date: 2019/12/19 6:39
 * @Version: 1.0
 */
public class TwoAdd {

    public static void main(String[] args){

        ListNode n1 = new ListNode(2);
        ListNode n2 = new ListNode(4);
        ListNode n3 = new ListNode(3);
        ListNode n = new ListNode(2);
        n2.next = n3;
        n1.next = n2;
        ListNode l1 = new ListNode(8);
        ListNode l2 = new ListNode(9);
        ListNode l3 = new ListNode(9);

        l1.next = l2;
        l2.next = l3;
        ListNode res = addTwoNumbers(n,l1);
        while (res != null){
            System.out.println(res.val + " ");
            res = res.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1,ListNode l2){
        ListNode node = new ListNode(0);
        ListNode cur = node;
        int n = 0;
        int t = 0;
        while (l1 != null || l2 != null){
            int v1 = l1 == null ? 0 : l1.val;
            int v2 = l2 == null ? 0 : l2.val;
            int val = v1 + v2;
            n = (val+t) % 10;
            cur.next = new ListNode(n);
            t = (val + t) / 10;
            if (l1 != null){
                l1 = l1.next;
            }
            if (l2 != null){
                l2 = l2.next;
            }
            cur = cur.next;
        }
        if (t > 0){
            cur.next = new ListNode(t);
        }

        return node.next;
    }
}
